package librus.cheeseChaser.components
{
	import feathers.display.Image;
	
	import flash.geom.Point;
	
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	import librus.cheeseChaser.tile.Move;
	import librus.cheeseChaser.tile.Tile;
	
	import librus.cheeseChaser.util.Assets;
	import librus.cheeseChaser.util.Sprite;
	
	public class Mat extends Sprite
	{
		public function Mat()
		{
			super();
		}
		
		private var bg:Image;
		private var holder:Holder;		
		private var oldSize:Point;
		
		override protected function startup():void
		{
			isListeningToResize = true;
			
			bg=new Image(Assets.getAtlas().getTexture("over"));
			addChild(bg);
			
			holder = new Holder;
			addChild(holder);
			
			oldSize = new Point(stage.stageWidth/2, stage.stageHeight/2);
			
			onResize();
			addEventListener(TouchEvent.TOUCH, touchHandler);			
		}
		
		private var startX:int;
		private var startY:int;
		
		private function touchHandler(event:TouchEvent):void
		{
			var touch:Touch = event.getTouch(stage);
			
			if (!touch)
				return;
			switch(touch.phase)
			{
				case TouchPhase.BEGAN:
					startX = touch.globalX;
					startY = touch.globalY;
					break;
				
				case TouchPhase.ENDED:
					startX = startY = 0;				
					break;
				
				case TouchPhase.MOVED:
					holder.x += touch.globalX - startX;
					holder.y += touch.globalY - startY;
					
					startX = touch.globalX;
					startY = touch.globalY;
					break;				
			}
		}
		
		override protected function onResize():void
		{			
			//TODO make it better
			holder.x = holder.x * bg.width / oldSize.x;
			holder.y = holder.y * bg.height / oldSize.y;			
		}
		
		public function addTile(value:Sprite, position:Point):void
		{
			position = holder.globalToLocal(position);
			value.x = position.x;
			value.y = position.y;
			
			holder.addChild(value);			
		}
		
		override public function set width(value:Number):void
		{			
			oldSize.x = bg.width;
			bg.width =value;	
		}
		
		override public function set height(value:Number):void			
		{
			oldSize.y = bg.height;
			bg.height = value;	
		}
		
		
		public function get centerTilePosition():Point
		{
			var child:Tile = holder.firstChild;
			return holder.localToGlobal(new Point(child.x,child.y));			
		}
		
		public function addMove(move:Move):void
		{
			addTile(move,new Point(move.x,move.y));
		}
		
		public function removeAllMoves():void
		{
			var child:Move;
			for (var i:int=holder.numChildren-1; i>=0; i--)
			{
				child = holder.getChildAt(i) as Move;
				if (child)
				{
					child.dispose();
					holder.removeChild(child);
				}
			}
		}
	}	
}